package com.zh.service.impl;

import cn.hutool.core.codec.Base62;
import cn.hutool.core.util.RandomUtil;
import com.zh.common.ErrorCode;
import com.zh.exception.ThrowUtils;
import com.zh.service.ShortLinkService;
import com.zh.utils.RedisUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class ShortLinkServiceImpl implements ShortLinkService {
    @Resource
    private RedisUtil redisUtil;


    /**
     * 生成短链
     *
     * @param url      原始 URL
     * @param domain   域名
     * @param time     过期时间
     * @param timeUnit 时间单位
     * @return 短链
     */
    @Override
    public String generateShortLink(String url, String domain, long time, TimeUnit timeUnit) {
        // 1.提取 domain/ 后的部分
        String path = url.substring(domain.length() + 1);
        // 2.生成短链标识符
        int randomStart = RandomUtil.randomInt(1, 20);
        String shortLink = Base62.encode(path).substring(randomStart, randomStart + 12);
        // 3.构建短链 URL
        String shortUrl = domain + "/link/" + shortLink;
        // 4.将短链标识符和原始 URL 存储在 Redis 中，并设置过期时间
        Map<String, String> hashMap = new HashMap<>();
        hashMap.put("url", url);
        redisUtil.setHash(SHORT_LINK_PREFIX + shortUrl, hashMap, time, timeUnit);
        return shortUrl;
    }

    @Override
    public String resolveShortLink(String url) {

        // 2.从 Redis 中获取原始 URL
        Map<String, String> hashEntries = redisUtil.getHashEntries(SHORT_LINK_PREFIX + url);
        ThrowUtils.throwIf(hashEntries == null, ErrorCode.OPERATION_ERROR, "链接已过期或无效");
        String originalUrl = hashEntries.get("url");
        ThrowUtils.throwIf(originalUrl == null, ErrorCode.OPERATION_ERROR, "链接已过期或无效");
        return originalUrl;
    }

    @Override
    public void distroShortLink(String url) {
        redisUtil.delete(SHORT_LINK_PREFIX + url);
    }
}
